/*
 * @Description: 描述信息
 * @Version: 版本号
 * @Author: xuebao
 * @Date: 2023-12-10 16:39:05
 * @LastEditors: xuebao
 * @LastEditTime: 2023-12-14 15:16:46
 */
import axios, { AxiosError, } from 'axios'
import { showLoading, hideLoading } from './loading'
import { getItem, removeItem } from '@/utils/storage'
import { Result } from '@/types/api';
import { message } from './AntdGlobal'
// console.log(import.meta.env);
import ENV from '@/config/index';
// console.log(ENV, 'env');

//创建实例
const instance = axios.create({
  // baseURL: import.meta.env.VITE_BASE_API,
  timeout: 8000,
  timeoutErrorMessage: '请求超时，请稍后',//如果不设置这个属性会有一个默认的文案
  withCredentials: true,
  headers: {
    icode: '346C9858606AB989'
  }
  //设置为true以后后端要设置Access-Control-Allow-Origin为你的源地址
  // 例如http://localhost:8080，不能是*，而且还要设置header(‘Access-Control-Allow-Credentials: true’);
})
// 拦截器分为请求拦截&响应拦截

//请求拦截器
instance.interceptors.request.use((config) => {

  if (config.showLoading) showLoading()
  const token = getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  if (import.meta.env.VITE_MOCK === 'true') {
    // config.baseURL = import.meta.env.VITE_MOCK_API
    config.baseURL = ENV.mockApi
  } else {
    // config.baseURL = import.meta.env.VITE_BASE_API
    config.baseURL = ENV.baseApi
  }
  return {
    ...config
  }
}, (error: AxiosError) => {
  Promise.reject(error)
})

//响应拦截器
instance.interceptors.response.use((response) => {
  const data: Result = response.data
  hideLoading()//请求成功以后关闭
  if (response.config.responseType === 'blob') return response
  if (data.code == 500001) {
    //token登陆失效
    removeItem('token')
    location.href = '/login?callback' + encodeURIComponent(location.href)//跳转到登陆页面
    message.error(data.msg)
  }

  if (data.code != 0) {
    if (response.config.showError == false) {
      return Promise.resolve(data)
    } else {
      message.error(data.msg)
      return Promise.reject(data)
    }

  }
  return data.data
}, (error) => {
  hideLoading()
  message.error(error.message)
  return Promise.reject(error.message)
})



interface IConfig {
  showLoading?: boolean,
  showError?: boolean
}
export default {

  get<T>(url: string, params?: object, options: IConfig = {
    showLoading: true,
    showError: true
  }): Promise<T> {
    return instance.get(url, { params, ...options })
  },

  post<T>(url: string, params?: object, options: IConfig = {
    showLoading: true,
    showError: true
  }): Promise<T> {
    return instance.post(url, params, { ...options })
  },
  downloadFile(url: string, data: any, fileName = 'fileName.xlsx') {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob',
    }).then((response) => {
      const blob = new Blob([response.data], {
        type: response.data.type
      })
      // const name =  (response.headers['file-name'] as string) || fileName
      const name = fileName
      const link = document.createElement('a')
      link.download = decodeURIComponent(name)
      link.href = URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(link.href)//释放

    })
  }
}

